# Copyright (c) 2009, Michal Mazurek
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
# 
#    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
#    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
#    * Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import sys, socket, socket, cPickle, time, traceback, logging
from __init__ import RequestedObjectDoesNotExists, NoObjectRequested


if __name__ == "__main__":
    logger = logging.getLogger("PyPickleRPCClient")
    logger.setLevel(logging.CRITICAL)
    
    fh = logging.handlers.SysLogHandler("/dev/log")
    
    formatter = logging.Formatter("%(name)s[%(process)s] %(message)s")
    fh.setFormatter(formatter)
    logger.addHandler(fh)


class RPCCallWrapper(object):
    
    def __init__(self, name, rpcclient):
        self.name = name
        self.rpcclient = rpcclient
        
    def __call__(self, *args, **kwds):
        request = (self.name, args, kwds)
        
        return self.rpcclient.send_request(request)
    

class RPCRequestObject(object):
    
    def __init__(self, rpcclient):
        self.rpcclient = rpcclient
    
    def __getattr__(self, name):
        
        return RPCCallWrapper(name, self.rpcclient)
    
    


class RPCClient(object):
    
    address_family = socket.AF_INET
    socket_type = socket.SOCK_STREAM
    
    def __init__(self, server_address):
        
        self.server_address = server_address
        self.connected = False
        self.connect()
        
    def get_server_object(self, name):
        
        self.send_request("", "Requested-Object:%s\n" % name)
        
        return RPCRequestObject(self)
        
    def connect(self):
        self.socket = socket.socket(self.address_family, self.socket_type)
        self.socket.connect(self.server_address)
        self.connected = True
        
    def setup(self):
        #self.rfile = self.socket.makefile('rb', 1024)
        #self.wfile = self.socket.makefile('wb', 1024)
        pass
    
    def finish(self):
        self.socket.close()

    def get_headers(self):
        char = ""
        headstring = ""
        while True:
            lastchar = char
            char = self.socket.recv(1)
            if char == "\n" and lastchar == "\n":
                break
            
            headstring += char
         
        headers = {}
        for line in headstring.splitlines():
            key, val = line.split(":")
            headers[key] = val
            pass
        
        self.headers = headers
        
        if "--debug" in sys.argv:
            logger.debug("Received Headers\n%s" % str(self.headers))
          
    def send_request(self, request, headers = ""):
        
        if not self.connected:
            self.connect()
            
        if request != "":
            pickle = cPickle.dumps(request)
        else:
            pickle = ""
        #print pickle
        contentlength = len(pickle)
        lenstr = "Content-Length:%d\n\n" % contentlength
        
        if "--debug" in sys.argv:
            logger.debug("Send Headers:\n%s" % headers+lenstr)
        
        self.socket.send(headers+lenstr+pickle)
        
        pickle= self.get_response()
        #print "="*40
        #print picklestr
        
        return pickle
    
    def get_response(self):
        
        self.get_headers()
        picklestr = ""
        
        contentlength = int(self.headers["Content-Length"])
        
        
        packetsize = 1024
        downloaded = 0
        buf = ""
        while True:
            if downloaded == int(contentlength):
                break
            
            if downloaded+packetsize > int(contentlength):
                packetsize = int(contentlength)-downloaded
            buf = self.socket.recv(packetsize)
            
            downloaded += packetsize
            picklestr = picklestr+buf
        try:
            pickle = cPickle.loads(picklestr)
        except EOFError:
            return None
        if self.headers.has_key("Traceback"):
            #self.finish()
            for line in traceback.format_list(pickle[2]):
                #print "DEBUG:", line
                logger.debug(line)
            raise pickle[0], pickle[1]
        
        
        return pickle
    def finish(self):
        
        finishheaders = "Finish-Connection:true\nContent-Length:0\n\n"
        
        self.socket.send(finishheaders)
        self.connected = False
        self.socket.close()
    

try:

    from M2Crypto import SSL
    import M2Crypto
        
    class SSLRPCClient(RPCClient):
        
        def __init__(self, server_address, cert, certkey, ca):
            
            self.cert = cert
            self.certkey = certkey
            self.ca = ca
    
            super(SSLRPCClient, self).__init__(server_address)
        
        def connect(self):
            global ca
            cert = self.cert
            certkey = self.certkey
            ca = self.ca
            def verify_cb(ok, store):
                global ca
                cert = store.get_current_cert()
                mecert = M2Crypto.X509.load_cert(ca)
                if mecert.get_fingerprint(md="sha1") == cert.get_fingerprint(md="sha1"):
                    return 1
                else:
                    return ok
            
            # setup an SSL context.
            context = SSL.Context("sslv23")
            context.load_verify_locations(ca, "./")
            context.set_verify(SSL.verify_peer | SSL.verify_fail_if_no_peer_cert, 1, verify_cb )
            #context.set_verify(SSL.verify_none, 1 )
            # load up certificate stuff.
            if "--debug" in sys.argv:
                logger.debug("Loaded cert file %s", cert)
            #context.use_privatekey_file(KEY_FILE)
            context.load_cert(cert, certkey)
            if "--debug" in sys.argv:
                context.set_info_callback()
                #context.set_info_callback()
            # make the socket
            real_sock = socket.socket(self.address_family, self.socket_type)
            connection = SSL.Connection(context, real_sock)
            #connection.set_accept_state()
           
            logger.info("Making connection to '%s:%s'" % self.server_address)
            self.socket = connection
            self.socket.connect(self.server_address)
            self.connected = True
            
except ImportError:
    class SSLRPCClient(object):

        def __init__(self, *args, **kw):
            print "Module M2Crypto is not installed."
            sys.exit(1)
    
if hasattr(socket, 'AF_UNIX'):
    
    class UnixRPCClient(RPCClient):
        
        address_family = socket.AF_UNIX
        
